package search.dfs;

/**
 * @Classname : NumberOfIslands
 * @Description : 200. 岛屿数量
 * https://leetcode.cn/problems/number-of-islands/
 * @Author : cty
 * @Date 2023/4/3 00:00
 */


public class NumberOfIslands {
    public int numIslands(char[][] grid) {
        int count = 0, m = grid.length, n = grid[0].length;
        boolean[][] visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    count++;
                    dfs(grid, m, n, visited, i, j);
                }
            }
        }
        return count;
    }

    private void dfs(char[][] grid, int m, int n, boolean[][] visited, int x, int y) {
        if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] || grid[x][y] == '0') return;

        visited[x][y] = true;
        dfs(grid, m, n, visited, x + 1, y);
        dfs(grid, m, n, visited, x - 1, y);
        dfs(grid, m, n, visited, x, y + 1);
        dfs(grid, m, n, visited, x, y - 1);
    }
}
